package com.inspect.quartz;

import java.text.ParseException;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

import com.inspect.log.LogSingleton;
import com.inspect.util.Constant;

public class JobSchedule {

	private static Scheduler scheduler = null;
	private static final Object lock = new Object();
	private static Logger logger = LogSingleton.get_logger(JobSchedule.class);

	public static Scheduler getSchedulerInstance() {
		if (scheduler == null) {
			synchronized (lock) {
				if (scheduler == null) {
					try {
						scheduler = StdSchedulerFactory.getDefaultScheduler();
					} catch (SchedulerException e) {
						logger.error("启动调度器",e);
						return null;
					}
				}
			}
		}
		return scheduler;
	}

	/**
	 * 添加任务
	 * 
	 * @param jobName任务名称
	 * @param jobGroup任务组名称
	 * @param jobClass任务类对象
	 * @param cronExpress定时调度表达式
	 */
	public void addJob(String jobName, String jobGroup, String triggerName,
			String triggerGroupName, Class jobClass, String cronExpress, Date startTime,
			Map<String, String> parameter) {

		try {
			JobDetail jobDetail = new JobDetail(jobName, jobGroup, jobClass);
			// 创建触发器对象，并为它设置名称，组名称，及任务调度的时间参数
			if (parameter != null && !parameter.isEmpty())
				jobDetail.getJobDataMap().put(Constant.CMD, parameter);
			CronTrigger cronTrigger = new CronTrigger(triggerName,
					triggerGroupName);
			cronTrigger.setStartTime(startTime);
			cronTrigger.setCronExpression(cronExpress);
			// 配置JobDetail和Trigger对象
			JobSchedule.getSchedulerInstance().scheduleJob(jobDetail,
					cronTrigger);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 启动调度器
	 */
	public void startScheduler() {
		try {
			if (!JobSchedule.getSchedulerInstance().isStarted()) {
				logger.info("-----开启调度中所有的job任务--");
				JobSchedule.getSchedulerInstance().start();
			}
		} catch (Exception e) {
			logger.error("-----启动调度job任务失败--" , e);
			throw new RuntimeException(e);
		}
	}

	/** */
	/**
	 * 移除一个任务
	 * 
	 * @param jobName
	 * @param jobGroupName
	 * @param triggerName
	 * @param triggerGroupName
	 * @throws SchedulerException
	 */
	public void removeJob(String jobName, String jobGroupName,
			String triggerName, String triggerGroupName) {
		try {
			if (JobSchedule.getSchedulerInstance().isStarted()) {
				JobSchedule.getSchedulerInstance().pauseTrigger(triggerName,
						triggerGroupName);// 停止触发器
				JobSchedule.getSchedulerInstance().unscheduleJob(triggerName,
						triggerGroupName);// 移除触发器
				JobSchedule.getSchedulerInstance().deleteJob(jobName,
						jobGroupName);// 删除任务
				logger.info("-----停止调度中所有的job任务--");
			}
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			logger.error("-----停止调度job任务失败--" + e);
			e.printStackTrace();
		}
	}

	public void editJob(String jobName, String jobGroup, String triggerName,
			String triggerGroupName, Class jobClass, String cronExpress, Date startTime,
			Map<String, String> parameter) {
		try {
			if (JobSchedule.getSchedulerInstance().isStarted()) {
				JobSchedule.getSchedulerInstance().pauseTrigger(triggerName,
						triggerGroupName);// 停止触发器
				JobSchedule.getSchedulerInstance().unscheduleJob(triggerName,
						triggerGroupName);// 移除触发器
				JobSchedule.getSchedulerInstance().deleteJob(jobName, jobGroup);// 删除任务
				// 增加新任务
				JobDetail jobDetail = new JobDetail(jobName, jobGroup, jobClass);
				// 创建触发器对象，并为它设置名称，组名称，及任务调度的时间参数
				if (parameter != null && !parameter.isEmpty())
					jobDetail.getJobDataMap().put(Constant.CMD, parameter);
				CronTrigger cronTrigger = new CronTrigger(triggerName,
						triggerGroupName);
				cronTrigger.setStartTime(startTime);
				cronTrigger.setCronExpression(cronExpress);
				// 配置JobDetail和Trigger对象
				JobSchedule.getSchedulerInstance().scheduleJob(jobDetail,
						cronTrigger);
				logger.info("-----修改调度中的job任务--");
			}
		} catch (SchedulerException e) {
			logger.error("-----修改调度job任务失败--" , e);
		} catch (ParseException e) {
			logger.error("-----修改调度job任务失败--" , e);
		}
	}

	/**
	 * @Description: 修改一个任务的触发时间(使用默认的任务组名，触发器名，触发器组名)
	 * 
	 * @param jobName
	 * @param time
	 */
	@SuppressWarnings("unchecked")
	public void modifyJobTime(String triggerName, String triggerGroupName,
			String time) {
		try {
			CronTrigger trigger = (CronTrigger) JobSchedule
					.getSchedulerInstance().getTrigger(triggerName,
							triggerGroupName);
			if (trigger == null) {
				return;
			}
			String oldTime = trigger.getCronExpression();
			if (!oldTime.equalsIgnoreCase(time)) {
				CronTrigger ct = (CronTrigger) trigger;
				// 修改时间
				ct.setCronExpression(time);
				// 重启触发器
				JobSchedule.getSchedulerInstance().resumeTrigger(triggerName,
						triggerGroupName);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
